package com.engc.common.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FTPUtil {

	private FTPClient client = null;

	private String remoteDir = "/";

	public boolean login(String host, Integer port, String user, String pwd) throws SocketException, IOException {
		return login(host, port, user, pwd, remoteDir);
	}

	/**
	 * 登陆
	 * 
	 * @param host
	 * @param user
	 * @param pwd
	 * @return
	 * @throws IOException
	 * @throws SocketException
	 */
	public boolean login(String host, int port, String user, String pwd, String remoteDir) throws SocketException, IOException {
		client = new FTPClient();
		// client.connect(host);
		client.connect(host, port);
		client.setControlEncoding("UTF-8");
		int reply = client.getReplyCode();
		client.setFileTransferMode(FTP.BINARY_FILE_TYPE);
		client.setConnectTimeout(0);
		if (!FTPReply.isPositiveCompletion(reply)) {
			client.disconnect();
			System.err.println("FTP server refused connection.");
		}
		this.remoteDir = remoteDir;
		client.enterLocalPassiveMode();
		return client.login(user, pwd);
	}

	public void close() throws IOException {
		if (client.isConnected()) {
			client.disconnect();
		}
	}

	/***
	 * 得到文件名
	 * 
	 * @return
	 */
	public List<String> getNames(boolean deep) {
		List<String> names = new ArrayList<String>();
		if (client != null) {
			names = checkDirectory(names, client, deep);
		}
		return names;
	}

	public List<FTPFile> getFTPFiles() throws IOException {
		List<FTPFile> list = new ArrayList<FTPFile>();
		if (client != null) {
			FTPFile[] files;
			files = client.listFiles(this.remoteDir);
			for (int i = 0; i < files.length; i++) {
				FTPFile file = files[i];
				String name = file.getName();
				if (name.equals(".") || name.equals("..")) {
					continue;
				} else if (file.isFile()) {
					list.add(file);
				}
			}
		}
		return list;
	}

	private List<String> checkDirectory(List<String> names, FTPClient client, boolean deep) {
		try {
			// System.out.println("---" + client.printWorkingDirectory());
			FTPFile[] files = client.listFiles(client.printWorkingDirectory());
			for (int i = 0; i < files.length; i++) {
				FTPFile file = files[i];
				// System.out.println(file.getTimestamp().getTime().toLocaleString());
				String name = file.getName();
				if (name.equals(".") || name.equals("..")) {
					continue;
				}

				if (deep && file.isDirectory()) {
					// System.out.println(client.printWorkingDirectory());
					if (client.changeWorkingDirectory(client.printWorkingDirectory() + "/" + name)) {
						names = checkDirectory(names, client, deep);
					}
					client.changeToParentDirectory();
				} else if (file.isFile()) {
					String d = client.printWorkingDirectory();
					d = (d.equals("/") ? "" : d);
					name = d + "/" + name;
					names.add(name);
				}

			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return names;
	}

	// filename 上传文件名
	// fullpath 全路径
	// ftpdir ftp服务器目录
	public boolean upload(InputStream fis, String filename, String ftpdir) {
		try {
			// 设置上传目录
			client.changeWorkingDirectory(ftpdir);
			client.setBufferSize(1024);
			client.setControlEncoding("UTF-8");
			// 设置文件类型（二进制）
			client.setFileType(FTPClient.BINARY_FILE_TYPE);
			return client.storeFile(filename, fis);

		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("FTP客户端出错！", e);
		} finally {
			try {
				client.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
				throw new RuntimeException("关闭FTP连接发生异常！", e);
			}
		}
	}

	/***
	 * 下载数据到指定的目录中
	 * 
	 * @param filename
	 *            ftp端文件名称
	 * @param local
	 *            客户端保存路劲
	 * @return
	 */
	public boolean download(String filename, String local) {
		boolean f = false;
		try {
			File file = new File(local + (filename.startsWith("/") ? filename : "/" + filename));
			File file2 = file.getParentFile();
			if (!file2.exists()) {
				file2.mkdirs();
			}
			file2 = null;
			client.setFileType(FTPClient.BINARY_FILE_TYPE);
			OutputStream out = new FileOutputStream(file);
			f = client.retrieveFile(this.remoteDir + "/" + filename, out);
			out.close();
			client.logout();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (client.isConnected()) {
				try {
					client.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return f;
	}

	public boolean downloadNClose(String filename, String local) throws Exception {
		try {
			File file = new File(local + (filename.startsWith("/") ? filename : "/" + filename));
			File file2 = file.getParentFile();
			if (!file2.exists()) {
				file2.mkdirs();
			}
			file2 = null;

			client.changeWorkingDirectory(remoteDir);
			client.setBufferSize(1024);
			client.setControlEncoding("UTF-8");

			// //判断是否存在
			// boolean flag = false;
			// FTPFile[] files = client.listFiles();
			// for(FTPFile ftpfile : files){
			// if(filename.equals(ftpfile.getName())){
			// flag = true;
			// break;
			// }
			// }
			// if(!flag){
			// return false;
			// }

			client.setFileType(FTPClient.BINARY_FILE_TYPE);
			OutputStream out = new FileOutputStream(file);
			boolean f = client.retrieveFile(this.remoteDir + "/" + filename, out);
			out.close();
			client.logout();
			return f;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			throw new Exception("ftp下载" + filename + "文件异常...");
		} catch (IOException e) {
			e.printStackTrace();
			throw new Exception("ftp下载" + filename + "文件异常...");
		} finally {
			if (client.isConnected()) {
				try {
					client.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 判断指定的文件夹或文件在指定目录是否存在
	 * 
	 * @param ftp
	 *            FtpClient
	 * @param RemotePath
	 *            String
	 * @param key
	 *            String
	 * @return boolean
	 */
	public boolean isExists(String filename, String ftpdir) throws Exception {
		// 设置上传目录
		boolean flag = false;
		try {
			client.changeWorkingDirectory(ftpdir);
			client.setBufferSize(1024);
			client.setControlEncoding("UTF-8");

			FTPFile[] files = client.listFiles();
			for (FTPFile file : files) {
				if (filename.equals(file.getName())) {
					flag = true;
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (client.isConnected()) {
				try {
					client.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return flag;
	}

	public static void main(String[] args) throws Exception {
		FTPUtil ftpUtil = new FTPUtil();
		try {
			// boolean c = ftpUtil.login("172.16.44.17",29, "engc111",
			// "Engc1234$", "/");
			boolean c = ftpUtil.login("172.16.17.250", 21, "server", "server", "/");
			System.out.println(c);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// FileInputStream fis = new FileInputStream(new File("d:\\22.png"));
		// ftpUtil.upload(fis, "22.png", "/");
		// ftpUtil.isExists("", "/logo");
		// if(ftpUtil.isExists("22.png", "/")){
		// ftpUtil.download("22.png", "d:\\33.png");
		// System.out.println("2323");
		// }
		// ftpUtil.downloadNClose(filename, local);
		System.out.println("over");
	}

	public String getRemoteDir() {
		return remoteDir;
	}

	public void setRemoteDir(String remoteDir) {
		this.remoteDir = remoteDir;
	}

}
